<?php
// +----------------------------------------------------------------------
// | 忠诚客户分析
// +----------------------------------------------------------------------
namespace app\admin\controller\v2;

use app\admin\Adminbase;
use base\files\Poster;
use app\admin\model\SystemParamValue;

class LoyalCustomer extends Adminbase{

	/**
	 * 获取忠诚客户数据
	*/
	public function index($shop_id, $date=''){
		try{
			$x = model("admin/system_param_value")
			->where('param_code', 'buess_shop_khfx_zckh')
			->where('parent_value', $shop_id)
			->value('param_value') ?? '0~100,100~500,500';

			$data['x'] = explode(',', $x);
			$data['y1'] = ['number'=>[], 'money'=>[]];
			$data['y2'] = ['number'=>[], 'money'=>[]];
			$data['maleTarget'] = ['nddcs'=>[], 'xfrs'=>[], 'rszb'=>[], 'xfje'=>[], 'xfzb'=>[], 'xfpjkdj'=>[]];
			$data['femaleTarget'] = ['nddcs'=>[], 'xfrs'=>[], 'rszb'=>[], 'xfje'=>[], 'xfzb'=>[], 'xfpjkdj'=>[]];
			
			foreach($data['x'] as $key => $value){
				$arr = explode("~",$value);

				$model = $this->getModel($shop_id, 1, $date);//每一次都搞个新的实例出来吗
				$totalNum = $model->count(); //想来想去，是的，拿来算到店次数占比的
				$totalXf = $model->sum('pay_price');//想来想去，是的，拿来消费占比的

				//随时随地定义变量并且赋值。。。。
				if( $arr[1] ){
					$data['y1']['number'][] = $num = $model
						->where('nums', '>=', $arr[0])
						->where('nums', '<', $arr[1])
						->count();
					$data['y1']['money'][] = $money = $model
						->where('nums', '>=', $arr[0])
						->where('nums', '<', $arr[1])
						->sum('pay_price');
					$data['maleTarget']['xfrs'][] = $num;
					$data['maleTarget']['rszb'][] = ($totalNum > 0 ? round($num / $totalNum * 100,2) : 0) .'%';
					$data['maleTarget']['xfje'][] = $money;
					$data['maleTarget']['xfzb'][] = ($totalXf > 0 ? round($money / $totalXf * 100,2) : 0) .'%';
					$data['maleTarget']['xfpjkdj'][] = ($num > 0 ? round($money / $num ,2) : 0);
					
				}else{
					$data['y1']['number'][] = $num = $model
						->where('nums', '>=', $arr[0])
						->count();
					$data['y1']['money'][] = $money = $model
						->where('nums', '>=', $arr[0])
						->sum('pay_price');
					
					$data['maleTarget']['xfrs'][] = $num;
					$data['maleTarget']['rszb'][] = ($totalNum > 0 ? round($num / $totalNum * 100,2) : 0) .'%';
					$data['maleTarget']['xfje'][] = $money;
					$data['maleTarget']['xfzb'][] = ($totalXf > 0 ? round($money / $totalXf * 100,2) : 0) .'%';
					$data['maleTarget']['xfpjkdj'][] = ($num > 0 ? round($money / $num ,2) : 0);
				}

				$model = $this->getModel($shop_id, 2, $date);//每一次都搞个新的实例出来吗
				$totalNum = $model->count(); //想来想去，是的，拿来算到店次数占比的
				$totalXf = $model->sum('pay_price');//想来想去，是的，拿来消费占比的

				//随时随地定义变量并且赋值。。。。
				if( $arr[1] ){
					$data['y2']['number'][] = $num = $model
						->where('nums', '>=', $arr[0])
						->where('nums', '<', $arr[1])
						->count();
					$data['y2']['money'][] = $money = $model
						->where('nums', '>=', $arr[0])
						->where('nums', '<', $arr[1])
						->sum('pay_price');
					
					$data['femaleTarget']['xfrs'][] = $num;
					$data['femaleTarget']['rszb'][] = ($totalNum > 0 ? round($num / $totalNum * 100, 2) : 0) .'%';
					$data['femaleTarget']['xfje'][] = $money;
					$data['femaleTarget']['xfzb'][] = ($totalXf > 0 ? round($money / $totalXf * 100, 2) : 0) .'%';
					$data['femaleTarget']['xfpjkdj'][] = ($num > 0 ? round($money / $num ,2) : 0);
				}else{
					$data['y2']['number'][] = $num = $model
						->where('nums', '>=', $arr[0])
						->count();
					$data['y2']['money'][] = $money = $model
						->where('nums', '>=', $arr[0])
						->sum('pay_price');
					
					$data['femaleTarget']['xfrs'][] = $num;
					$data['femaleTarget']['rszb'][] = ($totalNum > 0 ? round($num / $totalNum * 100, 2) : 0) .'%';
					$data['femaleTarget']['xfje'][] = $money;
					$data['femaleTarget']['xfzb'][] = ($totalXf > 0 ? round($money / $totalXf * 100, 2) : 0) .'%';
					$data['femaleTarget']['xfpjkdj'][] = ($num > 0 ? round($money / $num ,2) : 0);
				}

				if( !$arr[1] ) {
					$data['x'][$key] = $value.'以上';
				}
				$data['maleTarget']['nddcs'][] = $data['x'][$key];
				$data['femaleTarget']['nddcs'][] = $data['x'][$key];

			}	

			return $this->reSucess($data);
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());
		}
	}


	/**
	 * 设置忠诚客户
	*/
	public function set($shop_id, $data){
		try{
			$res = model("admin/system_param_value")
				->where('param_code', 'buess_shop_khfx_zckh')
				->where('parent_value', $shop_id)
				->delete();
			
			$res = model("admin/system_param_value")->save([
					'param_scope'=>'店铺参数',
					'param_code'=>'buess_shop_khfx_zckh',
					'parent_value'=>$shop_id,
					'param_value'=>$data
				]);
			return $this->reSucess(true);
		}catch(\Exception $e){
			return $this->ReError($e->getMessage());
		}
	}

	/**
	 * 获取忠诚客户
	*/
	public function get($shop_id){
		try{
			$result = model("admin/system_param_value")
				->where('param_code', 'buess_shop_khfx_zckh')
				->where('parent_value', $shop_id)
				->value('param_value')?? '';
			return $this->reSucess($result);
		}catch(\Exception $e){
			return $this->ReError($e->getMessage());
		}
	}


	//获取模型
	private function getModel($shop_id=-1, $sex=1, $dates=''){
		$sql = '1=1'; //给$sql赋默认值
		if( $dates ){
			$sql = 'add_time>='.explode(" - ", $dates)[0];
			$sql = $sql.' add_time<='.explode(" - ", $dates)[1];
		}

		//.  字符串模板连接符？
		//explode('', _str ) 类似这个str.split('')吧，区别是split是字符串对象的方法，explode应该是tp的扩展方法。
		//alias用于设置当前数据表的别名，便于使用其他的连贯操作例如join方法等。

		//LEFT JOIN: 即使右表中没有匹配，也从左表返回所有的行
		$model = model('user')->alias('a')
			->leftJoin("(
				select uid,sum(pay_price) pay_price from xw_order
				where is_pay = 1 and status >= 0
				and $sql
				group by uid
			) b", 'a.id = b.uid')
			->leftJoin("(
				select uid,add_time,count(*) nums from(
					select * from xw_shop_yy_order where status=1
					order by id desc
					limit 0,9999999999
				) a group by uid
			) c", 'c.uid = a.id') //为什么还要嵌套一层，不能直接select uid,add_time,count(*) nums from from xw_shop_yy_order where status=1吗？
			->where('a.shop_id', $shop_id)
			->where(
				function($query) use($sex){	//use是什么
					$query->where('a.sex', $sex);
					$query->whereor('a.sex', $sex == 1 ? '男' : '女');
				} 
			);
		return $model;
	}	
}